/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TrackerServlet;

import Database.TrackerDBHandler;
import FileStructure.FileHandler;
import FileStructure.Response;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.PeerEntity;

/**
 *
 * @author user
 */
public class ResponseServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
       private final int interval = 2;
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ReverseServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ReverseServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }
    private static String message = "Error during Servlet processing";

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        try {
            int len = req.getContentLength();
            byte[] input = new byte[len];

            ServletInputStream sin = req.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            }
            sin.close();

            String inString = new String(input);
            int index = inString.indexOf("=");
            if (index == -1) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(message);
                resp.getWriter().close();
                return;
            }
            String value = inString.substring(index + 1);

            //decode application/x-www-form-urlencoded string
            String decodedString = URLDecoder.decode(value, "UTF-8");

            String str = (new StringBuffer(decodedString)).toString();
            // set the response code and write the response data
            resp.setStatus(HttpServletResponse.SC_OK);
            String[] pecah = str.split(";;");
            OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());


            //writer.write("filename = " + pecah[0] + "; port = " + pecah[1] + "; uploaded = " + pecah[2] + "; downloaded = " + pecah[3] + "; event = " + pecah[4]);
            writer.write(this.processRequest(str));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            try {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().print(e.getMessage());
                resp.getWriter().close();
            } catch (IOException ioe) {
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public String processRequest(String str) {
        String[] parsed = str.split(";;");
        //simpan di database
        System.out.println("mysql pass = "+parsed[6]);
        TrackerDBHandler tr = new TrackerDBHandler(parsed[6]);
        String ret =this.interval+"##";
        ArrayList<PeerEntity> pe = new ArrayList<PeerEntity>();
        try {
            //insert ke file_stats
            //jika sudah ada, update
            //filename+";;"+port+";;"+uploaded+";;"+downloaded+";;left;;started";
            //cek event, jika completed, maka isi 1
            int compl = 0;
            if (parsed[5].equalsIgnoreCase("completed")){
                compl = 1;
            }
            tr.HandleShareFile("127.0.0.1", Integer.parseInt(parsed[1]), parsed[0], compl);
            tr.updateFileStats(Integer.parseInt(parsed[1]), parsed[0], Integer.parseInt(parsed[2]),
                                Integer.parseInt(parsed[3]), Integer.parseInt(parsed[4]));
        } catch (Exception ex) {
            Logger.getLogger(ResponseServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        //update file stats
//        tr.updateFileStats(interval, message, interval, interval, interval)

        //update record tabel list peer menjadi complete, jika ada file yg sudah selesai didownload
        pe = tr.HandleRequest(parsed[0]);

        for (int i=0; i< pe.size(); i++){
            int completed = 0;
            if (pe.get(i).isSeeder) completed = 1;
            ret =  ret + /*String.valueOf(pe.get(i).peer_id) + ";;" + */pe.get(i).IP +";;"+
                        String.valueOf(pe.get(i).port) + ";;" + String.valueOf(completed) + "##";
            //format : interval##ID;;IP;;Port;;completed;;
        }
        return ret;

    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
